﻿Public Class RunProcess
    Private Parent As Form
    Private mingWPath As String
    Private prc As Process = Nothing
    Private _isAlive As Boolean = False

    Public Event Exited()

    Public ReadOnly Property isAlive() As Boolean
        Get
            Return _isAlive
        End Get
    End Property

    Public Sub New(ByVal mingwPath As String, ByVal pParent As Form)
        Parent = pParent
        Me.mingWPath = mingwPath
    End Sub

    Public Function Run(ByVal file As String) As Boolean
        If prc Is Nothing Then
            prc = New Process()
            prc.StartInfo.FileName = "cb_console_runner.exe"
            prc.StartInfo.Arguments = """" & file & """"
            prc.StartInfo.EnvironmentVariables("PATH") &= ";" & mingWPath
            prc.StartInfo.UseShellExecute = False
            prc.EnableRaisingEvents = True

            AddHandler prc.Exited, AddressOf ProcessExited

            prc.Start()

            _isAlive = True
            Return True
        Else
            Return False
        End If
    End Function

    Public Sub StopProcess()
        If prc IsNot Nothing Then
            prc.Kill()
        End If
    End Sub

    Private Sub ProcessExited(ByVal sender As Object, ByVal e As EventArgs)
        RemoveHandler prc.Exited, AddressOf ProcessExited
        prc.Dispose()
        prc = Nothing
        _isAlive = False

        Parent.Invoke(RaiseExitedEventInvoke)
    End Sub

    Private Delegate Sub RaiseExitedEventDelegate()
    Private RaiseExitedEventInvoke As New RaiseExitedEventDelegate(AddressOf RaiseExitedEvent)
    Private Sub RaiseExitedEvent()
        RaiseEvent Exited()
    End Sub
End Class
